package com.jsgt.greekfire.ui.trading.dialog

import android.content.Context
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.PopupWindow
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemClickListener
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.jsgt.greekfire.R
import kotlin.collections.MutableList

class TradingCoinSelectPopup<T : TradingCoinSelectPopup.Type>(context: Context?) :
    PopupWindow(context) {
    var typeAdapter: TypeAdapter<T>? = null
    var data: MutableList<T>? = null
    var onItemClickListener: com.jsgt.greekfire.common.listener.OnItemClickListener<T>? = null

    init {
        contentView =
            LayoutInflater.from(context).inflate(R.layout.dialog_trading_coin_select, null)

        width = ViewGroup.LayoutParams.WRAP_CONTENT
        height = ViewGroup.LayoutParams.WRAP_CONTENT
        setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        isOutsideTouchable = true

        val recyclerView = contentView.findViewById<RecyclerView>(R.id.recycler)
        recyclerView.layoutManager = LinearLayoutManager(context)
        typeAdapter = TypeAdapter(R.layout.item_dialog_trading_coin_select, null)
        recyclerView.adapter = typeAdapter
        typeAdapter?.setOnItemClickListener(object : OnItemClickListener {
            override fun onItemClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
                typeAdapter?.setSPosition(position)
                dismiss()
                typeAdapter?.getItem(position)?.let { onItemClickListener?.onItemClick(it) }
            }
        })
    }

    fun refresh(data: MutableList<T>) {
        this.data = data
        typeAdapter?.setNewInstance(data)
    }

    class TypeAdapter<T : Type>(layoutResId: Int, data: MutableList<T>?) :
        BaseQuickAdapter<T, BaseViewHolder>(layoutResId, data) {
        var selectPosition = 0

        override fun convert(holder: BaseViewHolder, item: T) {
            holder.setText(R.id.txv, item.getText())
            holder.setTextColorRes(
                R.id.txv, if (selectPosition == holder.adapterPosition) {
                    R.color.text_trading_coin_dialog_s
                } else {
                    R.color.text_trading_coin_dialog
                }
            )
        }

        fun setSPosition(position: Int) {
            this.selectPosition = position
            notifyDataSetChanged()
        }
    }

    interface Type {
        fun getText(): String
    }
}